package com.py.credit.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.py.credit.common.LhjcConstants;
import com.py.credit.entity.FeedbackApiObj;
import com.py.credit.entity.QueryApiObj;
import com.py.credit.entity.SysUser;
import com.py.credit.service.*;
import com.py.credit.utils.DateUtil;
import com.py.credit.utils.IpUtil;
import com.py.framework.core.helper.JWTHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping(value = "/api")
public class LhjcApiController {

    @Autowired
    private LhjcApiService lhjcApiService;

    @Autowired
    private LhjcRemoteBaseService lhjcRemoteBaseService;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private SubjectCenterInterface subjectCenterInterface;

    @Autowired
    private FeedbackService feedbackService;

    /**
     * 联合奖惩获取主体信息接口
     *
     * @param queryData json格式的查询参数
     * @return
     */
    @RequestMapping(value = "/getSubject.json", method = RequestMethod.POST, consumes = {"application/json; charset=UTF-8", "text/plain; charset=UTF-8", "application/xml; charset=UTF-8"},
            produces = {"application/json; charset=UTF-8", "text/plain; charset=UTF-8", "application/xml; charset=UTF-8"})
    @ResponseBody
    public Map<String, Object> getSubject(@RequestBody String queryData,
                                          HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();

        if (StringUtils.isBlank(queryData)) {
            map.put("code", "2");
            map.put("msg", "必填参数不能为空");
            return map;
        }

        try {
            //json解析字符串
            JSONObject queryMap = JSON.parseObject(queryData);
            String loginName = queryMap.getString("loginName");
            String token = queryMap.getString("token");

            SysUser manager = lhjcRemoteBaseService.getByUsername(loginName);
            if (null == manager || "".equals(manager.getUsername())) {
                map.put("code", "2");
                map.put("msg", "登录名称不存在");
                return map;
            }

            String lhjcToken = lhjcRemoteBaseService.getLhjcToken(officeService.selectTopDeptId(manager.getOfficeId() + ""));
            if (StringUtils.isBlank(lhjcToken)) {
                map.put("code", "2");
                map.put("msg", "该用户所在部门还未授权");
                return map;
            }

            if (!lhjcToken.equals(token)) {
                map.put("code", "2");
                map.put("msg", "token不正确");
                return map;
            }

            JSONArray ztmcList = queryMap.getJSONArray("list");

            if (ztmcList.size() > 20) {
                map.put("code", "2");
                map.put("msg", "查询的主体信息个数超过限制");
                return map;
            }

            List<JSONObject> dataList = new ArrayList<JSONObject>();
            for (int i = 0; i < ztmcList.size(); i++) {
                JSONObject ztmcObject = ztmcList.getJSONObject(i);
                String type = ztmcObject.getString("ztType");
                if ("C".equals(type)) {
                    ztmcObject.put("heimdsl", lhjcApiService.getHongHeimdCount(ztmcObject.getString("name"), ztmcObject.getString("bm"), type, "C", IpUtil.getIpAddr(request), manager.getId()) + "");
                    ztmcObject.put("hongmdsl", lhjcApiService.getHongHeimdCount(ztmcObject.getString("name"), ztmcObject.getString("bm"), type, "J", IpUtil.getIpAddr(request), manager.getId()) + "");
                } else if ("P".equals(type)) {
                    ztmcObject.put("heimdsl", lhjcApiService.getHongHeimdCount(ztmcObject.getString("name"), ztmcObject.getString("bm"), type, "C", IpUtil.getIpAddr(request), manager.getId()) + "");
                    ztmcObject.put("hongmdsl", lhjcApiService.getHongHeimdCount(ztmcObject.getString("name"), ztmcObject.getString("bm"), type, "J", IpUtil.getIpAddr(request), manager.getId()) + "");
                } else {
                    ztmcObject.put("heimdsl", "0");
                    ztmcObject.put("hongmdsl", "0");
                }

                ztmcObject.remove("ztType");
                ztmcObject.put("type", type);
                dataList.add(ztmcObject);
            }

            map.put("code", 0);
            map.put("msg", "查询成功");
            map.put("data", dataList);
        } catch (Exception e) {
            map.put("code", -2);
            map.put("msg", "查询失败");
        }

        return map;
    }

    /**
     * 联合奖惩行政审批局获取数据接口
     * <p>
     * queryApiObj   企业名称/姓名（当主体类型为自然人时可不必选）
     * bm     统一社会信用代码/身份证编码（当主体类型为法人时可不必选）
     * ajbh   事件编号（可选）
     * jcType 奖惩类型：C:惩戒，J:激励（必选）
     * ztType 主体类型：C:法人，P:自然人（必选）
     * token  授权码:根据授权码知道是哪个用户及部门信息（必选）
     *
     * @return
     */
    @RequestMapping(value = "/xzspDetail.json", method = RequestMethod.POST, consumes = {"application/json; charset=UTF-8", "text/plain; charset=UTF-8", "application/xml; charset=UTF-8"},
            produces = {"application/json; charset=UTF-8", "text/plain; charset=UTF-8", "application/xml; charset=UTF-8"})
    @ResponseBody
    public Map<String, Object> getXzspDetail(@RequestBody QueryApiObj queryApiObj,
                                             HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();

        //判断参数是否为空
        if (null == queryApiObj) {
            map.put("code", "2");
            map.put("msg", "必填参数不能为空");
            return map;
        }

        if (StringUtils.isBlank(queryApiObj.getLoginName()) || StringUtils.isBlank(queryApiObj.getJcType()) || StringUtils.isBlank(queryApiObj.getZtType()) || StringUtils.isBlank(queryApiObj.getToken())) {
            map.put("code", "2");
            map.put("msg", "必填参数不能为空");
            return map;
        }

        if (!"C".equals(queryApiObj.getJcType()) && !"J".equals(queryApiObj.getJcType())) {
            map.put("code", "2");
            map.put("msg", "奖惩类型错误");
            return map;
        }

        if (!"C".equals(queryApiObj.getZtType()) && !"P".equals(queryApiObj.getZtType())) {
            map.put("code", "2");
            map.put("msg", "主体类型错误");
            return map;
        }

        if ("C".equals(queryApiObj.getZtType()) && StringUtils.isBlank(queryApiObj.getName())) {
            map.put("code", "2");
            map.put("msg", "企业名称不能为空");
            return map;
        }

        if ("P".equals(queryApiObj.getZtType()) && StringUtils.isBlank(queryApiObj.getBm())) {
            map.put("code", "2");
            map.put("msg", "身份证编码不能为空");
            return map;
        }

        SysUser manager = lhjcRemoteBaseService.getByUsername(queryApiObj.getLoginName());
        if (null == manager || "".equals(manager.getUsername())) {
            map.put("code", "2");
            map.put("msg", "登录名称不存在");
            return map;
        }

        String lhjcToken = lhjcRemoteBaseService.getLhjcToken(officeService.selectTopDeptId(manager.getOfficeId() + ""));
        if (StringUtils.isBlank(lhjcToken)) {
            map.put("code", "2");
            map.put("msg", "该用户所在部门还未授权");
            return map;
        }

        if (!lhjcToken.equals(queryApiObj.getToken())) {
            map.put("code", "2");
            map.put("msg", "token不正确");
            return map;
        }

        return lhjcApiService.getXzspDetail(queryApiObj.getName(), queryApiObj.getBm(), queryApiObj.getAjbh(), queryApiObj.getJcType(), queryApiObj.getZtType(), IpUtil.getIpAddr(request), manager.getId());
    }

    /**
     * 联合奖惩获取数据接口
     * <p>
     * name   企业名称/姓名（当主体类型为自然人时可不必选）
     * bm     统一社会信用代码/身份证编码（当主体类型为法人时可不必选）
     * ajbh   事件编号（可选）
     * jcType 奖惩类型：C:惩戒，J:激励（必选）
     * ztType 主体类型：C:法人，P:自然人（必选）
     * token  授权码:根据授权码知道是哪个用户及部门信息（必选）
     *
     * @return
     */
    @RequestMapping(value = "/detail.json", method = RequestMethod.POST, consumes = {"application/json; charset=UTF-8", "text/plain; charset=UTF-8", "application/xml; charset=UTF-8"},
            produces = {"application/json; charset=UTF-8", "text/plain; charset=UTF-8", "application/xml; charset=UTF-8"})
    @ResponseBody
    public Map<String, Object> getDetail(@RequestBody QueryApiObj queryApiObj,
                                         HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();

        //判断参数是否为空
        if (null == queryApiObj) {
            map.put("code", "2");
            map.put("msg", "必填参数不能为空");
            return map;
        }

        if (StringUtils.isBlank(queryApiObj.getLoginName()) || StringUtils.isBlank(queryApiObj.getJcType()) || StringUtils.isBlank(queryApiObj.getZtType()) || StringUtils.isBlank(queryApiObj.getToken())) {
            map.put("code", "2");
            map.put("msg", "必填参数不能为空");
            return map;
        }

        if (!"C".equals(queryApiObj.getJcType()) && !"J".equals(queryApiObj.getJcType())) {
            map.put("code", "2");
            map.put("msg", "奖惩类型错误");
            return map;
        }

        if (!"C".equals(queryApiObj.getZtType()) && !"P".equals(queryApiObj.getZtType())) {
            map.put("code", "2");
            map.put("msg", "主体类型错误");
            return map;
        }

        if ("C".equals(queryApiObj.getZtType()) && StringUtils.isBlank(queryApiObj.getName())) {
            map.put("code", "2");
            map.put("msg", "企业名称不能为空");
            return map;
        }

        if ("P".equals(queryApiObj.getZtType()) && StringUtils.isBlank(queryApiObj.getBm())) {
            map.put("code", "2");
            map.put("msg", "身份证编码不能为空");
            return map;
        }

        SysUser manager = lhjcRemoteBaseService.getByUsername(queryApiObj.getLoginName());
        if (null == manager || "".equals(manager.getUsername())) {
            map.put("code", "2");
            map.put("msg", "登录名称不存在");
            return map;
        }

        String deptId = officeService.selectTopDeptId(manager.getOfficeId() + "");
        String lhjcToken = lhjcRemoteBaseService.getLhjcToken(deptId);
        if (StringUtils.isBlank(lhjcToken)) {
            map.put("code", "2");
            map.put("msg", "该用户所在部门还未授权");
            return map;
        }

        if (!lhjcToken.equals(queryApiObj.getToken())) {
            map.put("code", "2");
            map.put("msg", "token不正确");
            return map;
        }

        return lhjcApiService.getDetail(queryApiObj.getLoginName(), queryApiObj.getName(), queryApiObj.getBm(), queryApiObj.getAjbh(), queryApiObj.getJcType(), queryApiObj.getZtType(), IpUtil.getIpAddr(request), manager.getId(), Long.parseLong(deptId));
    }

    @RequestMapping(value = "/feedback.json", method = RequestMethod.POST, consumes = {"application/json; charset=UTF-8", "text/plain; charset=UTF-8", "application/xml; charset=UTF-8"},
            produces = {"application/json; charset=UTF-8", "text/plain; charset=UTF-8", "application/xml; charset=UTF-8"})
    @ResponseBody
    public Map<String, Object> jcFeedback(@RequestBody FeedbackApiObj feedbackApiObj) {
        Map<String, Object> map = new HashMap<String, Object>();

        if (null == feedbackApiObj) {
            map.put("code", "2");
            map.put("msg", "必填参数不能为空");
            return map;
        }

        if (StringUtils.isBlank(feedbackApiObj.getLoginName()) || StringUtils.isBlank(feedbackApiObj.getMeasure()) || StringUtils.isBlank(feedbackApiObj.getFeedbackTime()) || StringUtils.isBlank(feedbackApiObj.getFeedbackMess()) || StringUtils.isBlank(feedbackApiObj.getJcType()) || StringUtils.isBlank(feedbackApiObj.getToken())) {
            map.put("code", "2");
            map.put("msg", "必填参数不能为空");
            return map;
        }

        if (!"C".equals(feedbackApiObj.getJcType()) && !"J".equals(feedbackApiObj.getJcType())) {
            map.put("code", "2");
            map.put("msg", "奖惩类型错误");
            return map;
        }

        SysUser manager = lhjcRemoteBaseService.getByUsername(feedbackApiObj.getLoginName());
        if (null == manager || "".equals(manager.getUsername())) {
            map.put("code", "2");
            map.put("msg", "登录名称不存在");
            return map;
        }

        String lhjcToken = lhjcRemoteBaseService.getLhjcToken(officeService.selectTopDeptId(manager.getOfficeId() + ""));
        if (StringUtils.isBlank(lhjcToken)) {
            map.put("code", "2");
            map.put("msg", "该用户所在部门还未授权");
            return map;
        }

        if (!lhjcToken.equals(feedbackApiObj.getToken())) {
            map.put("code", "2");
            map.put("msg", "token不正确");
            return map;
        }

        String[] arr = feedbackApiObj.getMeasure().split("_");

        if (arr.length == 0) {
            map.put("code", "2");
            map.put("msg", "请选择至少一条措施");
            return map;
        }

        try {
            // 缓存用户会话信息
            String lhjcRedisToken = JWTHelper.createJWT(String.valueOf(manager.getId()), manager.getUsername(), LhjcConstants.NUMBER_ZERO);
            subjectCenterInterface.putUserSessionData(lhjcRedisToken, manager);

            Map<String, Set<String>> ajbhMap = this.getAjbhMap(arr);
            for (Map.Entry<String, Set<String>> entry : ajbhMap.entrySet()
                    ) {
                feedbackService.addFeedback(entry.getKey(), DateUtil.getInstance().dateToStr(DateUtil.getInstance().getMinuteDate(feedbackApiObj.getFeedbackTime(), DateUtil.YYYY_MM_DD), DateUtil.YYYY_MM_DD_HH_MM_SS), feedbackApiObj.getFeedbackMess(), subjectCenterInterface.getCfbmByAjbh(entry.getKey()) + "", new ArrayList<String>(entry.getValue()), manager, lhjcRedisToken);
            }

            // 清除用户会话信息
            subjectCenterInterface.clearUserSessionData(lhjcRedisToken);

            map.put("code", "0");
            map.put("msg", "反馈成功");
        } catch (Exception e) {
            map.put("code", "2");
            map.put("msg", "反馈失败");
        }

        return map;
    }

    private Map<String, Set<String>> getAjbhMap(String arr[]) {
        Map<String, Set<String>> ajbhMap = new HashMap<String, Set<String>>();

        for (int i = 0; i < arr.length; i++) {
            String[] value = arr[i].split("-");
            List<String> ajbhList = Arrays.asList(value[1].split(","));
            for (String ajbh : ajbhList
                    ) {
                if (ajbhMap.containsKey(ajbh)) {
                    ajbhMap.get(ajbh).add(value[0]);
                } else {
                    Set<String> csSet = new HashSet<String>();
                    csSet.add(value[0]);
                    ajbhMap.put(ajbh, csSet);
                }
            }
        }

        return ajbhMap;
    }
}
